package com.fs.gateway.filter;

import com.ec.common.utils.UserContext;
import com.fs.gateway.config.AuthProperties;
import com.fs.gateway.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import lombok.RequiredArgsConstructor;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

@Configuration
@RequiredArgsConstructor
@EnableConfigurationProperties(AuthProperties.class)
public class AuthGlobalFilter implements GlobalFilter, Ordered {
    private final AuthProperties authProperties;
    private final AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 1. 获取 Request
        ServerHttpRequest request = exchange.getRequest();

        // 2. 判断是否不需要拦截
        if (isExclude(request.getPath().toString())) {
            return chain.filter(exchange);
        }

        // 3. 获取请求头中的 token
        String token = null;
        List<String> headers = request.getHeaders().get("token");
        if (headers != null && !headers.isEmpty()) {
            token = headers.get(0);
        }

        // 4. 校验并解析 token
        if (token == null || token.isEmpty()) {
            return unauthorizedResponse(exchange, "缺少 token");
        }

        String userId;
        try {
            Claims claims = JwtUtil.parseToken(token);
            userId = claims.getSubject();
        } catch (Exception e) {
            return unauthorizedResponse(exchange, "token 非法");
        }

        // 5. 存储 userId 到 UserContext
        try {
            UserContext.setUser(Long.parseLong(userId));
        } catch (NumberFormatException e) {
            return unauthorizedResponse(exchange, "无效的 userId");
        }

        // 6. 打印当前转发路由（调试用）
        System.out.println("当前转发路由：" + request.getPath());
        System.out.println("当前用户：" + UserContext.getUser());

        // 7. 继续执行下一个 filter
        ServerWebExchange swe = exchange.mutate()
                .request(builder -> builder.header("user-info", userId))
                .build();

        return chain.filter(swe);
    }

    // 判断是否为排除路径
    private boolean isExclude(String antPath) {
        for (String pathPattern : authProperties.getExcludePaths()) {
            if (antPathMatcher.match(pathPattern, antPath)) {
                return true;
            }
        }
        return false;
    }

    // 返回 401 响应
    private Mono<Void> unauthorizedResponse(ServerWebExchange exchange, String message) {
        ServerHttpResponse response = exchange.getResponse();
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
        String errorBody = "{\"error\": \"" + message + "\"}";
        return response.writeWith(Mono.just(response.bufferFactory().wrap(errorBody.getBytes())));
    }

    @Override
    public int getOrder() {
        return 0;
    }
}